package com.mshop.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.mshop.fw.util.SecurityUtil;

public class CookieUtil {

	protected static Logger log = Logger.getLogger(CookieUtil.class);

	private HttpServletRequest request = null;

	private HttpServletResponse response = null;

	public CookieUtil(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}

	/**
	 * (non-Javadoc)
	 * 
	 */
	public void add(String cookieName, String cookieValue, int age,String userDomain) {
		String val = SecurityUtil.encrypt(cookieValue);
		Cookie c = new Cookie(cookieName, val);
		c.setMaxAge(age);
		c.setPath("/");
		if (!StringUtils.isEmpty(userDomain)) {
			c.setDomain(userDomain);
		}
		response.addCookie(c);
	}

	/**
	 * 
	 * @param req
	 * @param cookieName
	 * @return
	 */
	public String get(String cookieName, String defaultvalue) {
		String val =null;
		
		Cookie[] cookies = null;
		try {
			cookies = request.getCookies();
		} catch (IllegalArgumentException iae) {
			log.error("", iae);
		}
		if ((cookies == null) || (cookies.length == 0)) {
			val=defaultvalue;
		}
		if(cookies!=null){
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if (cookieName.equals(cookie.getName())){
					val=(cookie.getValue());
					break;
				}
			}
		}
		return SecurityUtil.decrypt(val);
	}
}
